package com.party.jackclientandroid.ui_home.activity;

import android.content.Context;
import android.graphics.PointF;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.party.jackclientandroid.BaseActivity;
import com.party.jackclientandroid.R;
import com.party.jackclientandroid.adapter.item_view_delegate.ShopDetail_BaseMessageItem;
import com.party.jackclientandroid.adapter.item_view_delegate.ShopDetail_ConsumerRebateHeader;
import com.party.jackclientandroid.adapter.item_view_delegate.ShopDetail_ConsumerRebateItem;
import com.party.jackclientandroid.adapter.item_view_delegate.ShopDetail_DiscountPayBillItem;
import com.party.jackclientandroid.adapter.item_view_delegate.ShopDetail_GroupBuyItem;
import com.party.jackclientandroid.adapter.item_view_delegate.ShopDetail_GroupHeadItem;
import com.party.jackclientandroid.adapter.item_view_delegate.ShopDetail_HallMeal;
import com.party.jackclientandroid.adapter.item_view_delegate.ShopDetail_NavigationItem;
import com.party.jackclientandroid.adapter.item_view_delegate.ShopDetail_NoUserCommentItem;
import com.party.jackclientandroid.adapter.item_view_delegate.ShopDetail_RecommendGoodsItem;
import com.party.jackclientandroid.adapter.item_view_delegate.ShopDetail_ReplaceMoneyCouponItem;
import com.party.jackclientandroid.adapter.item_view_delegate.ShopDetail_SecondKillCouponItem;
import com.party.jackclientandroid.adapter.item_view_delegate.ShopDetail_ShopDetailItem;
import com.party.jackclientandroid.adapter.item_view_delegate.ShopDetail_SpellingGroupCouponItem;
import com.party.jackclientandroid.adapter.item_view_delegate.ShopDetail_UserCommentItem;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.api.ShopService;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.CommonResult;
import com.party.jackclientandroid.bean.DisplayableItem;
import com.party.jackclientandroid.bean.DiscountPayBillBean;
import com.party.jackclientandroid.bean.GroupTitleBean;
import com.party.jackclientandroid.bean.HallMeal;
import com.party.jackclientandroid.bean.NoUserComment;
import com.party.jackclientandroid.bean.RebateHeader;
import com.party.jackclientandroid.bean.RecommendVegetableListBean;
import com.party.jackclientandroid.bean.ShopDetail;
import com.party.jackclientandroid.bean.ShopDetailRebateBean;
import com.party.jackclientandroid.bean.ShopDetail_Header;
import com.party.jackclientandroid.bean.ShopDetail_NavigationBean;
import com.party.jackclientandroid.loadviewhelper.load.LoadViewHelper;
import com.party.jackclientandroid.utils.DateUtils;
import com.party.jackclientandroid.utils.DensityUtils;
import com.party.jackclientandroid.utils.Utils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 商家详情
 */
public class ShopDetailActivity extends BaseActivity {
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.navigation_ll)
    LinearLayout navigation_ll;
    @BindView(R.id.tab_1)
    TextView tab_1;
    @BindView(R.id.tab_2)
    TextView tab_2;
    @BindView(R.id.tab_3)
    TextView tab_3;

    String shopId;
    ShopService shopService;
    ShopDetailAdapter commonAdapter;
    List<DisplayableItem> mDataList;
    private Map<String, List<ShopDetailRebateBean>> weekModelList;
    private ShopDetail shopDetail;
    private LinearLayoutManager linearLayoutManager;
    private int couponCount = 0;
    private int commentCount = 0;
    //目标项是否在最后一个可见项之后
    private boolean mShouldScroll;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_detail);
        initData();
        initView();
    }

    protected void initData() {
        shopId = getIntent().getStringExtra("shopId");
        mDataList = new ArrayList<>();
        shopService = new ShopService(this);
        helper = new LoadViewHelper(mRefreshLayout);
        helper.setListener(() -> {
            helper.showLoading();
            getShopDetail();
        });
        helper.showLoading();
        getShopDetail();
    }

    public void initView() {
        mRefreshLayout.setEnableLoadMore(false);
        mRefreshLayout.setEnableRefresh(false);
        linearLayoutManager = new LinearLayoutManagerWithSmoothScroller(this);
        commonAdapter = new ShopDetailAdapter(this, mDataList);
        mRecyclerView.setAdapter(commonAdapter);
        mRecyclerView.addOnScrollListener(new RecyclerViewListener());
        mRecyclerView.setLayoutManager(linearLayoutManager);
    }

    public class LinearLayoutManagerWithSmoothScroller extends LinearLayoutManager {

        public LinearLayoutManagerWithSmoothScroller(Context context) {
            super(context, VERTICAL, false);
        }

        @Override
        public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
                                           int position) {
            RecyclerView.SmoothScroller smoothScroller = new TopSnappedSmoothScroller(recyclerView.getContext());
            smoothScroller.setTargetPosition(position);
            startSmoothScroll(smoothScroller);
        }

        private class TopSnappedSmoothScroller extends LinearSmoothScroller {
            public TopSnappedSmoothScroller(Context context) {
                super(context);

            }

            @Override
            public PointF computeScrollVectorForPosition(int targetPosition) {
                return LinearLayoutManagerWithSmoothScroller.this
                        .computeScrollVectorForPosition(targetPosition);
            }

            @Override
            protected int getVerticalSnapPreference() {
                return SNAP_TO_START;
            }
        }
    }

    public String getShopId() {
        return shopId;
    }

    public void setShopId(String shopId) {
        this.shopId = shopId;
    }

    //取消关注
    public void cancelAttention(ShopDetail_Header shopDetail, final ImageView attention_iv) {
        addDisposableIoMain(shopService.cancelAttention(shopId), new DefaultConsumer<CommonResult>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<CommonResult> result) {
                attention_iv.setImageResource(R.mipmap.not_attention_state);
                shopDetail.setIsAttention(0);
            }
        });
    }

    //关注
    public void addAttention(ShopDetail_Header shopDetail, final ImageView attention_iv) {
        addDisposableIoMain(shopService.addAttention(shopId + ""), new DefaultConsumer<CommonResult>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<CommonResult> result) {
                attention_iv.setImageResource(R.mipmap.attention_state);
                shopDetail.setIsAttention(1);
            }
        });
    }

    public String changeTime(String stampStr) {
        int stamp = Integer.parseInt(stampStr);
        int time = stamp % (24 * 60);
        int hour = time / 60;
        int min = time % 60;
        return (hour > 9 ? hour : "0" + hour) + ":" + (min > 9 ? min : "0" + min);
    }

    public String changeToTime(ShopDetail bean) {
        List<ShopDetailRebateBean> rebateDiscounts = shopDetail.getRebateDiscounts();
        ShopDetailRebateBean shopDetailRebateBean;
        for (int i = 0; i < rebateDiscounts.size(); i++) {
            shopDetailRebateBean = rebateDiscounts.get(i);
        }

//        shopDetailRebateBean.getStartTimeAxis();
//        shopDetailRebateBean.getEndTimeAxis();

        //获取当前时间
        int currentTime = DateUtils.getCurrentWeekIndex() * 24 * 60 + DateUtils.getCurrentTime();
        String reult = null;
        reult = null;
        for (int i = 0; i < rebateDiscounts.size(); i++) {
            ShopDetailRebateBean item = rebateDiscounts.get(i);
            if (Integer.parseInt(item.getStartTimeAxis()) > currentTime && Integer.parseInt(item.getEndTimeAxis()) < currentTime) {
                String disStr = Utils.changeStr100(item.getDiscount());
                reult = "返利" + disStr + "(" + changeTime(item.getStartTimeAxis() + "") + "~" + changeTime(item.getEndTimeAxis() + ")");
                break;
            }
        }
        if (reult == null) {
            if (bean.getRebateDiscount() == null) {
                reult = "暂无折扣";
            } else {
                reult = "返利" + Utils.changeStr100(bean.getRebateDiscount()) + "%";
            }
        }

        return reult;
    }

    public void getShopDetail() {
        mDataList.clear();
        addDisposableIoMain(shopService.getShopDetail(shopId), new DefaultConsumer<ShopDetail>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<ShopDetail> result) {
                //添加布局
                shopDetail = result.getData();

                mDataList.add(getShopDetail_header(shopDetail));
                mDataList.add(new ShopDetail_NavigationBean("导航条"));

                priseRebateData(mDataList);


                //面对对象Bean实现接口
                initRebateWeeks(mDataList);
//                if (shopDetail.getSecondKills().size() > 0) {
//                    couponCount += shopDetail.getSecondKills().size();
//                    mDataList.addAll(shopDetail.getSecondKills());
//                }
//
//                if (shopDetail.getCoupons().size() > 0) {
//                    couponCount += shopDetail.getCoupons().size();
//                    mDataList.addAll(shopDetail.getCoupons());
//                }

                if (shopDetail.getSecondKills().size() != 0 && shopDetail.getCoupons().size() != 0) {
                    mDataList.add(new HallMeal(""));
                }
//                if (shopDetail.getSpellingGroups().size() > 0) {
//                    couponCount += shopDetail.getSpellingGroups().size();
//                    mDataList.addAll(shopDetail.getSpellingGroups());
//                }
//                if (shopDetail.getGroupBuys().size() > 0) {
//                    couponCount += shopDetail.getGroupBuys().size();
//                    mDataList.addAll(shopDetail.getGroupBuys());
//                }
                if (shopDetail.getItems().size() > 0) {
                    RecommendVegetableListBean recommendVegetableListBean = new RecommendVegetableListBean();
                    recommendVegetableListBean.setItemsBeanList(shopDetail.getItems());
                    mDataList.add(recommendVegetableListBean);
                }
                GroupTitleBean groupTitleBean = new GroupTitleBean();
                groupTitleBean.setGroupName("用户评价");
                groupTitleBean.setHead(true);
                groupTitleBean.setShowRightArrow(true);
                mDataList.add(groupTitleBean);
                if (shopDetail.getComments().size() > 0) {
                    mDataList.addAll(shopDetail.getComments());
                    commentCount = shopDetail.getComments().size();
                } else {
                    mDataList.add(new NoUserComment("没有评论"));
                }
                mDataList.add(shopDetail);
                commonAdapter.notifyDataSetChanged();
                mRefreshLayout.finishRefresh();
                helper.showContent();
            }
        });
    }


    private void priseRebateData(List<DisplayableItem> mDataList) {
        // 首单显示数据。
        String disCount = shopDetail.getDiscount() + "";
        // 非首单，显示数据
        String disMessage = changeToTime(shopDetail) + "";
        //
        String totalComsumeNumber = shopDetail.getTotalComsumeNumber() + "";

        mDataList.add(new DiscountPayBillBean(shopDetail.getId(), disMessage, disCount, totalComsumeNumber));

    }

    /**
     * 处理消费返利  星期 的界面
     *
     * @param dataList
     */
    private void initRebateWeeks(List<DisplayableItem> dataList) {
        if (shopDetail.getRebateDiscount() == null && shopDetail.getRebateDiscounts().size() == 0)
            return;
        RebateHeader rebateHeader = new RebateHeader(shopDetail.getRebateDiscount());
        rebateHeader.setCurrentWeek(DateUtils.getCurrentWeekIndex());
        rebateHeader.setRadioOnClickListener((RadioGroup group, @IdRes int checkedId) -> {
            for (int i = 0; i < group.getChildCount(); i++) {
                if (group.getChildAt(i).getId() == checkedId) {
                    changeRebateWeeks(mDataList, i);
                    commonAdapter.notifyDataSetChanged();
                }
            }
        });
        //如果 折扣和 特殊时间都没有，就直接返回。

        //添加折扣到商品详情
        dataList.add(rebateHeader);
        weekModelList = inflateWeekData(shopDetail.getRebateDiscounts());
        if (weekModelList.get(DateUtils.getCurrentWeekIndex() + "") != null) {
            dataList.addAll(weekModelList.get(DateUtils.getCurrentWeekIndex() + ""));
        }
    }

    /**
     * 将数据插入到 星期的下面
     *
     * @param mDataList
     * @param index
     */
    private void changeRebateWeeks(List<DisplayableItem> mDataList, int index) {
        List<ShopDetailRebateBean> shopDetailRebateBeans = weekModelList.get(index + "");
        //先清空原来的折扣信息;
        Iterator<DisplayableItem> iterator = mDataList.iterator();
        while (iterator.hasNext()) {
            DisplayableItem next = iterator.next();
            if (next instanceof ShopDetailRebateBean) {
                iterator.remove();
            }
        }

        //如果没有渠道折扣信息就，设置默认的折扣信息
        if (shopDetailRebateBeans != null) {
            for (int i = 0; i < mDataList.size(); i++) {
                DisplayableItem displayableItem = mDataList.get(i);
                if (displayableItem instanceof RebateHeader) {
                    mDataList.addAll(i + 1, shopDetailRebateBeans);
                    return;
                }
            }
        }
    }

    /**
     * 将周的数据，转换成 map 数据，这样可以通过 周的索引获取该 天的 打折数据
     *
     * @param rebateList
     * @return
     */
    private Map<String, List<ShopDetailRebateBean>> inflateWeekData(List<ShopDetailRebateBean> rebateList) {
        weekModelList = new HashMap<>();
        for (int i = 0; i < rebateList.size(); i++) {
            ShopDetailRebateBean rebateBean = rebateList.get(i);
            int week = rebateBean.getWeek();
            List<ShopDetailRebateBean> rebateModels1 = weekModelList.get(week + "");
            if (rebateModels1 != null) {
                //取出最后一个对象 判断是否右侧有数据
                ShopDetailRebateBean lastBean = rebateModels1.get(rebateModels1.size() - 1);
                if (lastBean.getRightShopDetailRebateBean() == null) {
                    lastBean.setRightShopDetailRebateBean(rebateBean);
                } else {
                    rebateModels1.add(rebateBean);
                }
            } else {
                rebateModels1 = new ArrayList<>();
                rebateModels1.add(rebateBean);
                weekModelList.put(week + "", rebateModels1);
            }
        }
        //如果这个天，没有折扣，就传入默认的数据。
        for (int i = 0; i < 7; i++) {
            List<ShopDetailRebateBean> beanLines = weekModelList.get(i + "");
            if (beanLines == null) {
                List<ShopDetailRebateBean> weekBean = new ArrayList<>();
                String rebateDiscount = shopDetail.getRebateDiscount();
                if (rebateDiscount != null) {
                    ShopDetailRebateBean aDefault = ShopDetailRebateBean.getDefault(rebateDiscount);
                    aDefault.setStartTimeAxis(DateUtils.getCurrentWeekIndex() * 24 * 60 + shopDetail.getBussOpen() / 60 + "");
                    aDefault.setEndTimeAxis(DateUtils.getCurrentWeekIndex() * 24 * 60 + shopDetail.getBussClose() / 60 + "");
                    weekBean.add(aDefault);
                    weekModelList.put(i + "", weekBean);
                }
            }
        }
        return weekModelList;
    }

    public ShopDetail_Header getShopDetail_header(ShopDetail shopDetail) {
        String str = JSON.toJSONString(shopDetail);
        ShopDetail_Header shopDetail_header = JSON.parseObject(str, ShopDetail_Header.class);
        return shopDetail_header;
    }

    public SmartRefreshLayout getmRefreshLayout() {
        return mRefreshLayout;
    }

    public void setmRefreshLayout(SmartRefreshLayout mRefreshLayout) {
        this.mRefreshLayout = mRefreshLayout;
    }

    class RecyclerViewListener extends RecyclerView.OnScrollListener {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (mShouldScroll && RecyclerView.SCROLL_STATE_IDLE == newState) {
                mShouldScroll = false;
                mRecyclerView.smoothScrollBy(0, -(DensityUtils.dip2px(mActivity, 50)));
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
            if (firstItem == 1) {
                View view = mRecyclerView.getChildAt(0);
                if (view.getTop() <= -(DensityUtils.sp2px(mActivity, 15))) {
                    navigation_ll.setVisibility(View.VISIBLE);
                } else {
                    navigation_ll.setVisibility(View.GONE);
                }
            } else if (firstItem > 1) {
                navigation_ll.setVisibility(View.VISIBLE);
            } else {
                navigation_ll.setVisibility(View.GONE);
            }
            /*if (firstItem == 12){
                View secondView = mRecyclerView.getChildAt(1);
                int top = secondView.getTop();
                mRecyclerView.smoothScrollBy(0,top-DensityUtils.dip2px(mActivity,50));
            }*/
            if (firstItem >= 1) {
                View secondView = mRecyclerView.getChildAt(1);
                int top = secondView.getTop();
                if (top <= DensityUtils.dip2px(mActivity, 50)) {
                    tab_1.setTextColor(getResources().getColor(R.color.color_f89f03));
                    tab_2.setTextColor(getResources().getColor(R.color.color_8a8a8a));
                    tab_3.setTextColor(getResources().getColor(R.color.color_8a8a8a));

                    tab_1.setBackground(getResources().getDrawable(R.drawable.shape_bottom_line));
                    tab_2.setBackground(null);
                    tab_3.setBackground(null);
                }
            }
            if (firstItem >= 12) {
                View secondView = mRecyclerView.getChildAt(1);
                int top = secondView.getTop();
                if (top <= DensityUtils.dip2px(mActivity, 50)) {
                    tab_2.setBackground(getResources().getDrawable(R.drawable.shape_bottom_line));
                    tab_1.setBackground(null);
                    tab_3.setBackground(null);

                    tab_2.setTextColor(getResources().getColor(R.color.color_f89f03));
                    tab_1.setTextColor(getResources().getColor(R.color.color_8a8a8a));
                    tab_3.setTextColor(getResources().getColor(R.color.color_8a8a8a));
                }
                //mRecyclerView.smoothScrollBy(0,top-DensityUtils.dip2px(mActivity,50));
            }
        }
    }

    ;

    /**
     * 滑动到指定位置
     */
    public void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) {
        // 第一个可见位置
        int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
        // 最后一个可见位置
        int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1));
        if (position < firstItem) {
            // 第一种可能:跳转位置在第一个可见位置之前
            mRecyclerView.smoothScrollToPosition(position);
            mShouldScroll = true;

        } else if (position <= lastItem) {
            // 第二种可能:跳转位置在第一个可见位置之后
            int movePosition = position - firstItem;
            if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) {
                int top = mRecyclerView.getChildAt(movePosition).getTop();
                mRecyclerView.smoothScrollBy(0, top - DensityUtils.dip2px(mActivity, 50));
                //mRecyclerView.smoothScrollBy(0, top);
            }
        } else {
            // 第三种可能:跳转位置在最后可见项之后
            mRecyclerView.smoothScrollToPosition(position);
            mShouldScroll = true;
        }
    }


    public int getCouponCount() {
        return couponCount;
    }


    public RecyclerView getmRecyclerView() {
        return mRecyclerView;
    }

    public void setmRecyclerView(RecyclerView mRecyclerView) {
        this.mRecyclerView = mRecyclerView;
    }

    public int getCommentCount() {
        return commentCount;
    }


    @OnClick({R.id.tab_1, R.id.tab_2, R.id.tab_3})
    public void handleClickSth(View view) {
        switch (view.getId()) {
            case R.id.tab_1:
                clickTab(1);
                smoothMoveToPosition(mRecyclerView, 3);
                break;
            case R.id.tab_2:
                clickTab(2);
                smoothMoveToPosition(mRecyclerView, getCouponCount() + 4);
                break;
            case R.id.tab_3:
                clickTab(3);
                smoothMoveToPosition(mRecyclerView, getCouponCount() + 4 + getCommentCount());
                break;
        }
    }

    public void clickTab(int index) {
        switch (index) {
            case 1:
                tab_1.setTextColor(getResources().getColor(R.color.color_f89f03));
                tab_2.setTextColor(getResources().getColor(R.color.color_8a8a8a));
                tab_3.setTextColor(getResources().getColor(R.color.color_8a8a8a));

                tab_1.setBackground(getResources().getDrawable(R.drawable.shape_bottom_line));
                tab_2.setBackground(null);
                tab_3.setBackground(null);
                break;
            case 2:
                tab_2.setBackground(getResources().getDrawable(R.drawable.shape_bottom_line));
                tab_1.setBackground(null);
                tab_3.setBackground(null);

                tab_2.setTextColor(getResources().getColor(R.color.color_f89f03));
                tab_1.setTextColor(getResources().getColor(R.color.color_8a8a8a));
                tab_3.setTextColor(getResources().getColor(R.color.color_8a8a8a));
                break;
            case 3:
                tab_3.setBackground(getResources().getDrawable(R.drawable.shape_bottom_line));
                tab_1.setBackground(null);
                tab_2.setBackground(null);

                tab_3.setTextColor(getResources().getColor(R.color.color_f89f03));
                tab_1.setTextColor(getResources().getColor(R.color.color_8a8a8a));
                tab_2.setTextColor(getResources().getColor(R.color.color_8a8a8a));
                break;
        }
    }


    class ShopDetailAdapter extends MultiItemTypeAdapter<DisplayableItem> {

        public ShopDetailAdapter(Context context, List<DisplayableItem> datas) {
            super(context, datas);
            addItemViewDelegate(new ShopDetail_ShopDetailItem(context));//商品详情
            addItemViewDelegate(new ShopDetail_DiscountPayBillItem(context));//优惠买单
            addItemViewDelegate(new ShopDetail_ConsumerRebateHeader(context));//消费返利
            addItemViewDelegate(new ShopDetail_ConsumerRebateItem(context));//消费返利Item
            addItemViewDelegate(new ShopDetail_ReplaceMoneyCouponItem(context));//代金券Item
            addItemViewDelegate(new ShopDetail_SecondKillCouponItem(context));//秒杀券Item
            addItemViewDelegate(new ShopDetail_HallMeal(context));//堂食套餐
            addItemViewDelegate(new ShopDetail_SpellingGroupCouponItem(context));// 拼团券Item
            addItemViewDelegate(new ShopDetail_GroupBuyItem(context));//套餐券Item
            addItemViewDelegate(new ShopDetail_RecommendGoodsItem(context));//推荐商品
            addItemViewDelegate(new ShopDetail_GroupHeadItem(context));//推荐菜
            addItemViewDelegate(new ShopDetail_UserCommentItem(context));//用户评价
            addItemViewDelegate(new ShopDetail_BaseMessageItem(context));//基础信息
            addItemViewDelegate(new ShopDetail_NavigationItem(context));//导航栏 优惠情况  用户评论 商家信息
            addItemViewDelegate(new ShopDetail_NoUserCommentItem(context));//用户评论
        }
    }

}
